package com.ittx.dzt.shein.service.semi;


import cn.hutool.core.collection.CollectionUtil;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.shein.constant.SheinSemiApiConstant;
import com.ittx.dzt.shein.handler.AbstractSheinSemiByTimeApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 售后单增量下载
 * <p>
 * cy.returnOrder.download.byTimeFrame
 * /open-api/return-order/list	查询退货单列表 https://open.sheincorp.com/zh/documents/apidoc/detail/3001281
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/8/6
 */
@Slf4j
@Service
public class SheinSemiReturnOrderDownloadByTimeService extends AbstractSheinSemiByTimeApiHandler<TimeFrameDTO> {

	private static final Integer DEFAULT_PAGE_SIZE = 30;

	@Autowired
	private SheinSemiReturnOrderDownloadByIdService sheinSemiReturnOrderDownloadByIdService;

	@Override
	public String getMqTopic() {
		return SheinSemiApiConstant.Rocket.SHEIN_SEMI_DOWNLOAD_AFTERSALE_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getSheinSemiMethod() {
		return "/open-api/return-order/list";
	}

	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.RETURNORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	public Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		// 判断是rds还是sdk
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		// sdk
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	public Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		// 探查成功时不返回完整数据,只返回数量
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);

	}

	@Override
	public Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String refundId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, String.valueOf(refundId));

	}

	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		//时间查询的维度类型：1：退货单下发给到商家的时间/ 2：买家申请退货时间/ 3：退货单更新时间
		params.put("queryType", 3);
		// yyyy-MM-dd HH:mm:ss 默认查询48小时以内数据
		params.put("startTime", localDateTimeToString(timeFrameDTO.getFrom()));
		// yyyy-MM-dd HH:mm:ss 默认查询48小时以内数据
		params.put("endTime", localDateTimeToString(timeFrameDTO.getTo()));
		params.put("pageSize", DEFAULT_PAGE_SIZE);
		// 状态过滤,暂时不支持
		//1：已关闭/ 2：已申请/ 3：已取消/ 5：已收货/ 6：已妥投/ 7：待交接/ 8：待SHEIN仓中转/ 9：已完成
		// List<Integer> statusList = CyUtil.getStatusList(platformApiParamDTO, "return");
		// params.put("returnOrderStatus",9);
		// 页码从1开始
		long page = 1;
		// 第一次查询，获取总页数
		params.put("page", page);
		Result<?> result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
		// 订单数量
		int total = Integer.parseInt(dataMap.get(RESULT_TOTAL).toString());
		// 探查模式只返回总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
		if (totalPage > 0) {
			// 倒序查询，防止漏单
			for (int i = totalPage - 1; i >= 1; i--) {
				// 页码从0开始
				params.put("page", i);
				result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
				if (result.hasError()) {
					return result;
				}
				resultMap = (Map<String, Object>) result.getData();
				dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
				List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("returnOrderList");
				if (CollectionUtil.isNotEmpty(list)) {
					// 分发数据到MQ，异步消费下载
					for (Map<String, Object> order : list) {
						String orderId = order.get("returnOrderNo").toString();
						sendToSplitTopic(platformApiParamDTO, orderId, logMap);
					}
				}
			}
		}
		return Result.success(logMap);
	}


	/**
	 * sdk
	 * <p>
	 * 根据订单号下载售后单 ------- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String refundId) {
		Result<?> result = sheinSemiReturnOrderDownloadByIdService.getRefundById(platformApiParamDTO, refundId);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}
}
